package logic

import (
	"context"
	"fmt"
	"vip-shop/cache"
	"vip-shop/model"
	"vip-shop/pkg"

	"vip-shop/shoprpc/internal/svc"
	"vip-shop/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *shoprpc.RegisterRequest) (*shoprpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user model.User
	model.DB.Where("mobile=?", in.Account).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("用户已注册请去登录")
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "captcha"+in.Account).Result()
	if in.CaptchaCode != result {
		return nil, fmt.Errorf("图形验证码错误")
	}
	//s, _ := cache.Rdb.Get(cache.Ctx, "sms"+in.Account).Result()
	//if in.SenSmsCode != s {
	//	return nil, fmt.Errorf("短信验证码错误")
	//}
	user = model.User{
		Mobile:   in.Account,
		Password: pkg.Md5str(in.Password),
	}
	model.DB.Debug().Create(&user)
	return &shoprpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
